<?php
/**
 * 
 *      $data = array(
 *           'ToUserName'=>'1111',
 *          'FromUserName'=>'222',
 *           'CreateTime'=>time(),
 *          'MsgType'=>'news',
 *          'ArticleCount'=>2,
 *          'Articles'=>array(array('Title'=>'标题1','Description'=>'描述1','PicUrl'=>'图片1','Url'=>链接1))
 *      );
 *       $xml = new XmlCreate();
 *      $xml->createXml($data);
 */
class XmlCreate extends XMLWriter{
    public function __construct($rootElementName = 'xml'){
//         $this->openUri('php://output');
		$this->openMemory();
        $this->setIndentString('  ');
        $this->setIndent(true);
        $this->startElement($rootElementName);
    }
    /**
     * 
     * @param array $source
     * @param bool $cDataTags
     */
    public function createXml($source , $cDataTags = true){
        if(is_array($source)){
            foreach ($source as $key=>$value){
            	$xml_key = $key;
            	if(is_numeric($key)){
            		$xml_key = 'item';
            	}
                if(is_array($value)){
                    $this->startElement($xml_key);
                    $this->createXml($value);
                    $this->endElement();
                }else{
                    $this->setElement($xml_key, $value ,$cDataTags);
                }
            }
        }
        //return  $this->getDocument();
    }
    /**
     *  
     * @param string $elementName
     * @param string or number $elementText
     * @param bool $cDataTags 
     */
    private function setElement($elementName , $elementText ,$cDataTags = true){
        $this->startElement($elementName);
        if(is_string($elementText)){
        	if($cDataTags){
        		$this->writeCdata($elementText);
        	}else{
        		$this->text($elementText);
        	}
        }else{
            $this->text($elementText);
        }
        $this->endElement();
    }
    
    public function getDocument(){
    	$this->endElement();
        return $this->outputMemory(false);
    }
    
}